<template>
	<div class="echart" :id="id" :style="{ float: 'left', width: '100%', height: '400px' }"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
	props: {
		id: String
	},
	methods: {
		initChart(name, yData) {
			let legendData = [];
			let seriesData = [];
			for (var i = 0; i < yData.length; i++) {
				legendData.push(yData[i].name);
				seriesData.push({
					name: yData[i].name,
					value: yData[i].value
				});
			}
			let getchart = echarts.init(document.getElementById(this.id));
			var option = {
				tooltip: {
					trigger: 'item',
					formatter: '{a} <br/>{b} : {c} ({d}%)'
				},
				legend: {
					// top: '3%',
					// left: 'center',
					type: 'scroll',
					orient: 'vertical',
					right: 10,
					top: 20,
					bottom: 20,
					formatter: function(params) {
						let tip1 = '';
						let tip = '';
						let le = params.length; //图例文本的长度
						if (le > 9) {
							//几个字换行大于几就可以了
							let l = Math.ceil(le / 9); //有些不能整除，会有余数，向上取整
							for (let i = 1; i <= l; i++) {
								//循环
								if (i < l) {
									//最后一段字符不能有\n
									tip1 += params.slice(i * 9 - 9, i * 9) + '\n'; //字符串拼接
								} else if (i === l) {
									//最后一段字符不一定够9个
									tip = tip1 + params.slice((l - 1) * 9, le); //最后的拼接在最后
								}
							}
							return tip;
						} else {
							tip = params; //前面定义了tip为空，这里要重新赋值，不然会替换为空
							return tip;
						}
					},
					data: legendData

					// selected: selected
				},
				series: [
					{
						name: name,
						type: 'pie',
						radius: '55%',
						center: ['40%', '50%'],
						itemStyle: {
							borderRadius: 10,
							borderColor: '#fff',
							borderWidth: 2
						},
						labelLine: {
							show: false
						},
						data: seriesData,
						// label: {
						// 	show: false,
						// 	position: 'center'
						// },
						emphasis: {
							label: {
								show: true,
								fontSize: '30',
								fontWeight: 'bold'
							},
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)'
							}
						}
					}
				]
			};

			getchart.setOption(option);
			//随着屏幕大小调节图表
			window.addEventListener('resize', () => {
				getchart.resize();
			});
		}
	}
};
</script>
